<template>
    <div class="sys-log-container flex flex-col">
        <a-card class="mb-2.5">
            <common-form
                :model="state.queryForm"
                name="log-form"
                @query="handleQuery"
                @reset="handleReset"
            >
                <a-form-item
                    label="开始时间"
                    name="startTime"
                    class="w-1/3"
                >
                    <a-date-picker
                        v-model:value="state.queryForm.startTime"
                        format="YYYY-MM-DD HH:mm:ss"
                        show-time
                        :show-time-options="{ format: 'HH:mm:ss' }"
                        placeholder="请选择开始时间"
                    />
                </a-form-item>
                <a-form-item
                    label="结束时间"
                    name="endTime"
                    class="w-1/3"
                >
                    <a-date-picker
                        v-model:value="state.queryForm.endTime"
                        format="YYYY-MM-DD HH:mm:ss"
                        show-time
                        :show-time-options="{ format: 'HH:mm:ss' }"
                        placeholder="请选择结束时间"
                    />
                </a-form-item>
            </common-form>
        </a-card>
        <a-card class="flex-1 card-table">
            <common-table 
                :columns="columns"
                :data="state.tableData"
                :pagination="state.pagination"
                :loading="state.loading"
                @change="handleTableChange"
            >
                <template #bodyCell="{ column, record }">
                    <template v-if="column.dataIndex === 'status'">
                        <a-tag color="green" v-if="record.status === 'Success'">成功</a-tag>
                        <a-tag color="red" v-if="record.status === 'Error'">失败</a-tag>
                        <a-tag color="orange" v-else>{{ record.status }}</a-tag>
                    </template>
                    <template v-if="column.dataIndex === 'logLevel'">
                        <a-tag color="red" v-if="record.logLevel === 'Error'">错误</a-tag>
                        <a-tag color="orange" v-if="record.logLevel === 'Warn'">警告</a-tag>
                        <a-tag color="blue" v-if="record.logLevel === 'Info'">信息</a-tag>
                        <a-tag color="purple" v-if="record.logLevel === 'Debug'">调试</a-tag>
                    </template>
                    <template v-if="column.dataIndex === 'elapsed'">
                        {{ record.elapsed }} ms
                    </template>
                    <template v-if="['requestParam', 'returnResult', 'message'].includes(column.dataIndex)">
                        <a-button
                            type="link"
                            class="truncate max-w-[200px]"
                            @click="handleOpenModal(record[column.dataIndex], column.dataIndex, column.title)"
                        >
                            {{ record[column.dataIndex] ? '查看详情' : '-' }}
                        </a-button>
                    </template>
                    <template v-if="column.dataIndex === 'httpMethod'">
                        <a-tag :color="record.httpMethod === 'GET' ? 'blue' : 'green'">
                            {{ record.httpMethod }}
                        </a-tag>
                    </template>
                </template>
            </common-table>

            <!-- 添加模态框组件 -->
            <a-modal
                v-model:visible="modalVisible"
                :title="modalTitle"
                :width="800"
                @ok="modalVisible = false"
                @cancel="modalVisible = false"
            >
                <template v-if="modalType === 'json'">
                    <pre class="json-pre">{{ formattedContent }}</pre>
                </template>
                <template v-else>
                    <p class="text-pre">{{ modalContent }}</p>
                </template>
            </a-modal>
        </a-card>
    </div>
</template>

<script setup lang="ts" name="sysOpLog">
import { onMounted, reactive, ref, computed } from 'vue';
import CommonForm from '@/components/common-form/index.vue';
import CommonTable from '@/components/common-table/index.vue';
import type { ResType } from '@/api/types';
import { GetLogOptPage } from '@/api/sys/syslog';
import { showMsg } from '@/utils';
import type { TableParamsResType } from '../../onlineUser/type';

defineOptions({
    name:"sysOpLog"
})

const state = reactive({
    queryForm: {
        startTime: null as Date | null,
        endTime: null as Date | null
    },
    tableData: [] as any[],
    loading: false,
    pagination: {
        page: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: (total) => `共 ${total} 条记录`
    }
});

const columns = [
    { title: '序号', dataIndex: 'index', key: 'index', width: 60, align: 'center', customRender: ({ index }) => index + 1 },
    { title: '账号', dataIndex: 'account', key: 'account', width: 150 },
    { title: '真实姓名', dataIndex: 'realName', key: 'realName', width: 150 },
    { title: '请求方式', dataIndex: 'httpMethod', key: 'httpMethod', width: 90, align: 'center' },
    { title: '请求地址', dataIndex: 'requestUrl', key: 'requestUrl', width: 200 ,ellipsis: true},
    { title: '模块名称', dataIndex: 'controllerName', key: 'controllerName', width: 120,ellipsis: true },
    { title: '方法名称', dataIndex: 'actionName', key: 'actionName', width: 120 },
    { title: '显示名称', dataIndex: 'displayTitle', key: 'displayTitle', width: 250 },
    { title: '执行状态', dataIndex: 'status', key: 'status', width: 90, align: 'center' },
    { title: '日志级别', dataIndex: 'logLevel', key: 'logLevel', width: 90, align: 'center',ellipsis: true },
    { title: '请求参数', dataIndex: 'requestParam', key: 'requestParam', width: 180,ellipsis: true },
    { title: '日志时间', dataIndex: 'logDateTime', key: 'logDateTime', width: 180, align: 'center' },
    { title: '返回结果', dataIndex: 'returnResult', key: 'returnResult', width: 180,ellipsis: true },
    { title: '日志消息', dataIndex: 'message', key: 'message', width: 180 ,ellipsis: true},
    { title: '账号', dataIndex: 'account', key: 'account', width: 100 },
    { title: 'IP地址', dataIndex: 'remoteIp', key: 'remoteIp', width: 130 ,ellipsis: true},
    { title: '操作用时', dataIndex: 'elapsed', key: 'elapsed', width: 90, align: 'center' },
    { title: '跟踪ID', dataIndex: 'traceId', key: 'traceId', width: 180,ellipsis: true },
];

const handleQuery = async () => {
    state.loading = true;
    try {
        // 调用API获取操作日志数据
        const res = await GetLogOptPage({
            page: state.pagination.page,
            pageSize: state.pagination.pageSize,
            ...state.queryForm
        }) as ResType<TableParamsResType<any>>;

        if (res.data.code == 200) {
            state.tableData = res.data.result.items;
            state.pagination.total = res.data.result.total;
        } else {
            showMsg(res.data.message || '获取操作日志数据失败', 'error');
        }
    } catch (error) {
        showMsg('获取操作日志数据异常', 'error');
        console.error('获取操作日志数据异常:', error);
    } finally {
        state.loading = false;
    }
};

const handleReset = () => {
    state.queryForm.startTime = null;
    state.queryForm.endTime = null;
    state.pagination.page = 1;
    handleQuery();
};

const handleTableChange = (pagination: any) => {
    state.pagination.page = pagination.current;
    state.pagination.pageSize = pagination.pageSize;
    handleQuery();
};

// 日期格式化辅助函数
const formatDate = (date: Date): string => {
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
};

onMounted(() => {
    handleQuery();
});

// 添加模态框相关变量
const modalVisible = ref(false);
const modalContent = ref('');
const modalType = ref<'json' | 'text'>('text');
const modalTitle = ref('');

// 格式化JSON内容
const formattedContent = computed(() => {
  if (modalType.value === 'json') {
    try {
      const parsed = JSON.parse(modalContent.value);
      return JSON.stringify(parsed, null, 2);
    } catch (e) {
      return modalContent.value;
    }
  }
  return modalContent.value;
});

// 打开模态框的方法
const handleOpenModal = (content: string, dataIndex: string, title: string) => {
  modalContent.value = content || '无数据';
  modalType.value = ['requestParam', 'returnResult'].includes(dataIndex) ? 'json' : 'text';
  modalTitle.value = title;
  modalVisible.value = true;
};
</script>

<style lang="scss" scoped>
.sys-log-container {
    .card-table {
        :deep(.ant-card-body) {
            height: 100%;
            padding: 16px;
        }
    }
}

:deep(.ant-form-item) {
    margin-bottom: 16px;
}

:deep(.ant-table-cell) {
    white-space: nowrap;
}

.json-pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  background-color: #f5f5f5;
  padding: 16px;
  border-radius: 4px;
  max-height: 500px;
  overflow-y: auto;
  font-family: monospace;
}

.text-pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  line-height: 1.5;
  overflow-y: auto;
   max-height: 500px;
}
</style>